<template>
  <div class="select_city">
    <el-cascader
      v-model="cityValue"
      :props="selectCity"
      :show-all-levels="false"
			@change="getCity"
      clearable
    />
  </div>
</template>

<script setup>
import { ref, watch, defineProps, defineEmits } from "vue";
import api from "@api/config";

const emit = defineEmits(['setCityCode'])

const props = defineProps({
  value: {
    type: String
  },
});

watch(() => props.value, val => {
  if (val) {
		cityValue.value = [val.substring(0, 2) + '0000000', val]
	}
})

const cityValue = ref([])

const selectCity = {
  lazy: true,
  lazyLoad: function (node, resolve) {
    const { level, value } = node;
    api.area(value, level + 1, (val) => {
      resolve(
        val.map((e) => {
          e.leaf = level >= 1;
          return e;
        })
      );
    });
  },
};

function getCity(value) {
  if (value) {
    emit('setCityCode', value[1])
  } else {
    emit('setCityCode', null)
  }
}
</script>

